package com.andy.nicefi.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.andy.nicefi.bean.User;
import com.andy.nicefi.exception.LogException;
import com.andy.nicefi.manager.UserManager;
import com.andy.nicefi.service.UserService;
import com.andy.nicefi.util.StringUtil;

public class UserServiceImpl implements UserService{
	
	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	private UserManager userManager;

	public List<User> getAllUserList() {
		return userManager.getUserList();
	}

	public void saveUser(User user) {
		try {
			String password = user.getPassword();
			String md5Password = StringUtil.getMD5String(password);
			user.setPassword(md5Password);
			userManager.save(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void deleteUser(User user) {
		userManager.delete(user);
	}

	public void deleteUser(String userId) {
		userManager.delete(userId);
	}
	
	public void updateUser(User user) {
		userManager.update(user);
	}
	
	public boolean existUser(String hql) {
		return userManager.exist(hql);
	}
	
	public boolean validateLogin(User user) throws LogException {
		String findUserbyName = "from User where username='"+user.getUsername()+"'";
		String findUserbyEmail = "from User where email='"+user.getUsername()+"'";
		
		boolean existUserbyName = existUser(findUserbyName);
		boolean existUserbyEmail = existUser(findUserbyEmail);
		if(!existUserbyName && !existUserbyEmail) {
			throw new LogException(LogException.USER_NOT_EXIST);
		}
		User realUser = null;
		if(existUserbyName) {
			realUser = userManager.getUser(findUserbyName);
		}
		if(existUserbyEmail) {
			realUser = userManager.getUser(findUserbyEmail);
		}

		String md5Password = StringUtil.getMD5String(user.getPassword());
		if(!md5Password.equals(realUser.getPassword())) {
			throw new LogException(LogException.PASSWORD_NOT_CORRECT);
		}
		
		if(!realUser.isActive()) {
			throw new LogException(LogException.USER_NOT_ACTIVE);
		}
		return true;
	}
	
	public boolean activate(String key) throws LogException {
		User user = userManager.getUser("from User where email='"+key+"'");
		if(user == null)
			throw new LogException(LogException.USER_NOT_EXIST);
		if(user.isActive())
			throw new LogException(LogException.USER_ACTIVATED_ALREADY);
		user.setActive(true);
		userManager.update(user);
		return true;
	}
	
	@Transactional
	public User getUser(String hql) {
		return userManager.getUser(hql);
	}
	
	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

}
